import React, { useRef, useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import styles from './index.module.less';

const Pand = (props) => {
  const { theta1, theta2 } = props;

  const divRef = useRef(null);

  const [style, setStyle] = useState(null);

  const func = (w, h, theta) => {
    let x = 0;
    let y = 0;
    if (theta <= 45) {
      y = h - (w / 2) * Math.tan((theta * Math.PI) / 180);
    }
    if (theta > 45 && theta <= 90) {
      x = w / 2 - h * Math.tan(((90 - theta) * Math.PI) / 180);
    }
    if (theta > 90 && theta < 135) {
      x = w / 2 + h * Math.tan(((theta - 90) * Math.PI) / 180);
    }
    if (theta >= 135) {
      x = w;
      y = h - w / 2 / Math.tan(((theta - 90) * Math.PI) / 180);
    }
    return { x, y };
  };

  useEffect(() => {
    const min = Math.min(theta1, theta2);
    const max = Math.max(theta1, theta2);
    const w = 516;
    const h = 258;
    const { x: lx, y: ly } = func(w, h, min);
    const { x: rx, y: ry } = func(w, h, max);
    if ((lx === 0 && rx === 0) || (lx === w && rx === w)) {
      setStyle({ clipPath: `polygon(${lx}px ${ly}px, 50% 100%, ${rx}px ${ry}px)` });
    } else {
      setStyle({ clipPath: `polygon(0 0, ${lx}px ${ly}px, 50% 100%, ${rx}px ${ry}px, 100% 0)` });
    }
  }, [theta1, theta2]);

  return (
    <div className={styles.root} ref={divRef}>
      <div className={styles.inner} style={style} />
    </div>
  );
};

Pand.defaultProps = {
  theta1: 45,
  theta2: 135,
};

Pand.propTypes = {
  theta1: PropTypes.number,
  theta2: PropTypes.number,
};

export default Pand;
